package com.exthirteen.textgamescript.config;

import com.exthirteen.textgamescript.model.vo.Result;
import com.exthirteen.textgamescript.model.vo.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @Resource
    private HttpServletRequest request;

    /**
     * 业务逻辑异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({BaseException.class})
    public Result<?> methodArgumentNotValid(BaseException exception) {
        log.error("业务逻辑异常，错误信息: {}, 请求的URL: {}", exception, request.getRequestURI());
        return Result.error(exception.getCode(), exception.getMessage());
    }


    /**
     * ServletException异常处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ServletException.class)
    public Result<?> exceptionHandler(ServletException ex, HttpServletResponse response) {
        log.error("错误日志:" + ex.getMessage(),ex);
        response.setStatus(500);
        return Result.error(ResultStatus.REQUEST_NOT_ACCEPTED);
    }

    /**
     * 全局异常处理，反正异常返回统一格式的Result
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public Result<?> exceptionHandler(Throwable ex, HttpServletResponse response) {
        log.error("错误日志:" + ex.getMessage(),ex);
        return Result.error(ResultStatus.REQUEST_TIMEOUT);
    }

    /**
     * 添加@Validated 注解，异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        assert fieldError != null;
        log.error("参数非空判断field::{}，message:{}", fieldError.getField(), fieldError.getDefaultMessage());
        return Result.error(ResultStatus.ERROR_PARAM.getCode(), fieldError.getDefaultMessage());
    }
}
